#!/usr/bin/perl
use strict;
use XML::RAI;
use Digest::MD5 qw(md5_hex);
use XML::RAI::Enclosure;
use HTTP::Request;
use LWP::UserAgent;
use Config::INI::Simple;

my $config = new Config::INI::Simple;
$config->read($ENV{"HOME"}."/.tvtorrentsrc") or die($!);

my $rai = XML::RAI->parse_uri($config->{tvtorrents}->{feed});

foreach my $item (@{$rai->items})
{
    open FH, $ENV{"HOME"}."/".$config->{tvtorrents}->{regexps} or die($!);
    while(<FH>)
    {
	#my $regexp = eval(m/$_/i);
	chomp;
	if($item->title =~ m/$_/i)
	{
	    my $downloadsFile;
	    my $torrentFile;
	    if($item->title =~ m/(proper|repack)/i)
	    {
		$downloadsFile = $ENV{"HOME"}."/.tvtorrents/downloaded/".md5_hex($item->description).".".$1;
		$torrentFile = $ENV{"HOME"}."/.tvtorrents/".md5_hex($item->description).".".$1.".torrent";
	    }
	    else
	    {
		$downloadsFile = $ENV{"HOME"}."/.tvtorrents/downloaded/".md5_hex($item->description);
		$torrentFile = $ENV{"HOME"}."/.tvtorrents/".md5_hex($item->description).".torrent";
	    }
	    if(!-f $downloadsFile)
	    {
		for my $e (XML::RAI::Enclosure->load($item)) 
		{
		    print $item->title.":".$e->url, "\n";
		    my $ua = LWP::UserAgent->new;
		    my $torrentReq = HTTP::Request->new(GET=>$e->url);
		    my $torrent = $ua->request($torrentReq);
		    if($torrent->is_success)
		    {
 			open FH, ">$torrentFile" or die($!);
 			print FH $torrent->content."\n";
 			close FH;
 			open FH, ">$downloadsFile" or die($!);
 			print FH "moo";
 			close FH;
		    }
		    else
		    {
			print $torrent->status_line;
		    }
		}
	    }
	}
    }
}
